<template>
  <el-dialog
    v-model="dialogVisible"
    title="导出为Vue项目"
    width="550px"
    :before-close="handleClose"
  >
    <div class="export-form">
      <h4>配置项目信息</h4>
      
      <el-form label-position="top" :model="exportConfig">
        <el-form-item label="项目名称">
          <el-input 
            v-model="exportConfig.projectName" 
            placeholder="请输入项目名称"
            :maxlength="30"
            show-word-limit
          />
        </el-form-item>
        
        <el-form-item label="项目标题">
          <el-input 
            v-model="exportConfig.title" 
            placeholder="请输入项目标题"
          />
        </el-form-item>
        
        <el-form-item label="画布尺寸">
          <div class="size-inputs">
            <el-input-number 
              v-model="exportConfig.canvasSize.width" 
              :min="300" 
              :max="2000" 
              controls-position="right"
            />
            <span>×</span>
            <el-input-number 
              v-model="exportConfig.canvasSize.height" 
              :min="200" 
              :max="2000" 
              controls-position="right"
            />
            <span>px</span>
          </div>
        </el-form-item>
        
        <el-form-item label="画布样式">
          <div class="canvas-style-preview" :style="canvasStylePreview"></div>
          <div class="style-info">
            <div>背景色: {{ exportConfig.canvasStyle.backgroundColor }}</div>
            <div>边框: {{ exportConfig.canvasStyle.borderWidth }}px {{ exportConfig.canvasStyle.borderStyle }} {{ exportConfig.canvasStyle.borderColor }}</div>
          </div>
        </el-form-item>
        
        <el-divider />
        
        <el-form-item>
          <el-switch
            v-model="exportConfig.includeBackend"
            active-text="包含后端API"
            inactive-text="仅前端项目"
          />
          <div class="switch-hint" v-if="exportConfig.includeBackend">
            将生成一个包含Express后端的完整项目
          </div>
        </el-form-item>
        
        <el-divider />
        
        <el-form-item v-if="canBuild">
          <el-switch
            v-model="exportConfig.buildAfterExport"
            active-text="导出后自动构建"
            inactive-text="仅导出源码"
          />
          <div class="switch-hint" v-if="exportConfig.buildAfterExport">
            构建过程需要下载依赖，将耗费一些时间
          </div>
        </el-form-item>
        
        <template v-if="exportConfig.buildAfterExport && canBuild">
          <el-form-item label="构建设置">
            <div class="build-options">
              <el-checkbox v-model="exportConfig.buildOptions.useChineseRegistry">
                使用国内源下载依赖
              </el-checkbox>
              <el-tooltip content="使用缓存可以避免重复下载相同的依赖包，提高构建速度">
                <el-checkbox v-model="exportConfig.buildOptions.useCache">
                  使用依赖缓存
                </el-checkbox>
              </el-tooltip>
            </div>
          </el-form-item>
          
          <el-form-item label="构建模式">
            <el-radio-group v-model="exportConfig.buildOptions.buildMode">
              <el-radio label="development">开发模式</el-radio>
              <el-radio label="production">生产模式</el-radio>
            </el-radio-group>
            <div class="option-hint">
              生产模式将进行代码压缩和优化，构建时间较长
            </div>
          </el-form-item>
        </template>
      </el-form>
      
      <div class="export-notes">
        <h4>注意事项：</h4>
        <ul>
          <li>导出的Vue项目完整保留了组件的交互逻辑</li>
          <li>样式与原设计一致，包括位置、尺寸等属性</li>
          <li>项目基于Vite构建，包含完整的开发和构建配置</li>
          <li>可使用npm run dev命令启动开发服务器</li>
        </ul>
      </div>
    </div>
    
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleExport" :loading="exporting">
          {{ exporting ? (buildingProject ? '构建中...' : '导出中...') : '确认导出' }}
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watch, computed } from 'vue';
import { ElMessage } from 'element-plus';
import { useDesignStore } from '../stores/designStore';
import vueProjectExportService from '../services/VueProjectExportService';
import vueProjectBuilderService from '../services/VueProjectBuilderService';

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  }
});

const emit = defineEmits(['update:visible', 'close']);

// 对话框可见性
const dialogVisible = ref(props.visible);

// 导出中状态
const exporting = ref(false);
const buildingProject = ref(false);

// 是否可以构建项目
const canBuild = ref(false);

// 导出配置
const exportConfig = reactive({
  projectName: 'easy-window-export',
  title: 'Easy Window 导出项目',
  canvasSize: {
    width: 800,
    height: 600
  },
  canvasStyle: {
    backgroundColor: '#ffffff',
    borderWidth: 1,
    borderStyle: 'solid',
    borderColor: '#ddd',
    borderRadius: 4
  },
  includeBackend: false,
  buildAfterExport: false,
  buildOptions: {
    useChineseRegistry: true,
    useCache: true,
    buildMode: 'development'
  }
});

// 计算属性：画布样式预览
const canvasStylePreview = computed(() => {
  return {
    backgroundColor: exportConfig.canvasStyle.backgroundColor,
    border: `${exportConfig.canvasStyle.borderWidth}px ${exportConfig.canvasStyle.borderStyle} ${exportConfig.canvasStyle.borderColor}`,
    borderRadius: `${exportConfig.canvasStyle.borderRadius}px`,
    width: '100%',
    height: '40px'
  };
});

// 设计器store
const designStore = useDesignStore();

// 获取画布样式
const getCanvasStyles = () => {
  // 获取画布元素
  const canvasElement = document.querySelector('.canvas-content') as HTMLElement;
  
  if (canvasElement) {
    // 获取计算后的样式
    const computedStyle = window.getComputedStyle(canvasElement);
    
    // 更新样式配置
    exportConfig.canvasStyle = {
      backgroundColor: computedStyle.backgroundColor || '#ffffff',
      borderWidth: parseInt(computedStyle.borderWidth) || 1,
      borderStyle: computedStyle.borderStyle || 'solid',
      borderColor: computedStyle.borderColor || '#ddd',
      borderRadius: parseInt(computedStyle.borderRadius) || 4
    };
    
    console.log('获取到的画布样式:', exportConfig.canvasStyle);
  }
};

// 监听visible属性变化
watch(() => props.visible, (newVal) => {
  dialogVisible.value = newVal;
  
  // 当对话框打开时，更新配置
  if (newVal) {
    // 更新画布尺寸为当前画布尺寸
    const currentCanvasSize = designStore.canvasSize;
    exportConfig.canvasSize.width = currentCanvasSize.width;
    exportConfig.canvasSize.height = currentCanvasSize.height;
    
    // 获取当前画布样式
    getCanvasStyles();
  }
});

// 监听对话框可见性变化
watch(() => dialogVisible.value, (newVal) => {
  emit('update:visible', newVal);
  if (!newVal) {
    emit('close');
  }
});

// 关闭对话框
const handleClose = () => {
  if (buildingProject.value) {
    ElMessage.warning('项目正在构建中，请等待完成...');
    return;
  }
  dialogVisible.value = false;
};

// 执行导出
const handleExport = async () => {
  // 校验输入
  if (!exportConfig.projectName.trim()) {
    ElMessage.warning('请输入项目名称');
    return;
  }
  
  try {
    exporting.value = true;
    
    // 获取画布组件
    const components = [...designStore.canvasComponents];
    
    // 从组件数组中提取样式和属性
    const componentStyles: Record<string, any> = {};
    const componentProps: Record<string, any> = {};
    
    // 递归处理组件树，提取所有组件的样式和属性
    const extractStylesAndProps = (comps: any[]) => {
      comps.forEach(comp => {
        // 提取样式
        componentStyles[comp.id] = comp.style || {};
        
        // 提取属性
        componentProps[comp.id] = {
          datas: comp.props || {}
        };
        
        // 处理子组件
        if (comp.children && comp.children.length > 0) {
          extractStylesAndProps(comp.children);
        }
      });
    };
    
    // 处理所有组件
    extractStylesAndProps(components);
    
    // 导出选项
    const exportOptions = {
      projectName: exportConfig.projectName,
      title: exportConfig.title,
      canvasSize: exportConfig.canvasSize,
      includeBackend: exportConfig.includeBackend,
      // 控制是否自动保存文件
      saveFile: !exportConfig.buildAfterExport || !canBuild.value 
    };
    
    // 导出Vue项目
    const zipBlob = await vueProjectExportService.exportVueProject(
      {
        components,
        componentStyles,
        componentProps,
        canvasStyle: exportConfig.canvasStyle
      },
      exportOptions
    );
    
    // 如果不需要构建，完成导出后直接关闭对话框
    if (!exportConfig.buildAfterExport || !canBuild.value) {
      ElMessage.success('导出Vue项目成功！');
      dialogVisible.value = false;
      return;
    }
    
    // 需要构建项目，先保存ZIP到临时目录
    buildingProject.value = true;
    ElMessage.info('正在准备构建环境...');
    
    // 保存ZIP到临时目录并获取路径
    const saveResult = await window.electronAPI.invoke('save-blob-to-temp', {
      blob: await zipBlob.arrayBuffer(),
      filename: `${exportConfig.projectName}.zip`,
      extractAfterSave: true  // 解压ZIP文件
    });
    
    if (!saveResult.success) {
      throw new Error(`保存临时文件失败: ${saveResult.message}`);
    }
    
    // 构建项目
    const buildResult = await vueProjectBuilderService.buildProject(
      saveResult.extractPath, // 解压后的路径
      {
        useChineseRegistry: exportConfig.buildOptions.useChineseRegistry,
        skipCache: !exportConfig.buildOptions.useCache,
        buildMode: exportConfig.buildOptions.buildMode
      }
    );
    
    if (buildResult.success) {
      ElMessage.success('项目导出并构建成功！');
      // 打开输出目录 - 使用新的处理程序名称
      await window.electronAPI.invoke('open-build-output-folder', buildResult.outputPath);
    } else {
      // 构建失败，仍然保存源代码文件
      const FileSaver = await import('file-saver');
      FileSaver.saveAs(zipBlob, `${exportConfig.projectName}.zip`);
      ElMessage.warning('项目构建失败，但源代码已导出');
    }
    
    dialogVisible.value = false;
  } catch (error) {
    console.error('导出Vue项目失败:', error);
    ElMessage.error(`导出失败: ${error.message || '未知错误'}`);
  } finally {
    exporting.value = false;
    buildingProject.value = false;
  }
};

// 检查环境是否支持构建
const checkBuildSupport = async () => {
  try {
    // 检查是否支持构建
    canBuild.value = await vueProjectBuilderService.canBuildProject();
    
    // 如果环境不支持构建，禁用构建选项
    if (!canBuild.value) {
      exportConfig.buildAfterExport = false;
    }
    
    console.log('[VueProjectExportDialog] 环境支持构建项目:', canBuild.value);
  } catch (error) {
    console.error('[VueProjectExportDialog] 检查构建支持时出错:', error);
    canBuild.value = false;
    exportConfig.buildAfterExport = false;
  }
};

// 初始化
onMounted(async () => {
  // 初始化导出服务
  await vueProjectExportService.initialize().catch(error => {
    console.error('初始化Vue项目导出服务失败:', error);
  });
  
  // 初始化构建服务
  await vueProjectBuilderService.initialize().catch(error => {
    console.error('初始化Vue项目构建服务失败:', error);
  });
  
  // 检查是否支持构建
  await checkBuildSupport();
});
</script>

<style scoped>
.export-form {
  padding: 0 10px;
}

.size-inputs {
  display: flex;
  align-items: center;
  gap: 10px;
}

.canvas-style-preview {
  margin-bottom: 8px;
  border-radius: 4px;
}

.style-info {
  font-size: 12px;
  color: #666;
  margin-top: 4px;
}

.build-options {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}

.option-hint, 
.switch-hint {
  margin-top: 4px;
  color: #909399;
  font-size: 12px;
}

.export-notes {
  margin-top: 20px;
  padding: 16px;
  background-color: #f8f8f8;
  border-radius: 4px;
  color: #606266;
}

.export-notes h4 {
  margin-top: 0;
  margin-bottom: 10px;
  color: #303133;
}

.export-notes ul {
  margin: 0;
  padding-left: 20px;
}

.export-notes li {
  margin-bottom: 5px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 